package com.hancher.gamelife2.birthday;

import android.os.Bundle;

import androidx.navigation.Navigation;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.KeyEventUtil;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseMvpFragment;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.backup.BaiduNetApi;
import com.hancher.gamelife2.databinding.FragmentBirthdayListBinding;
import com.hancher.gamelife2.home.HomePresenter;
import com.hancher.gamelife2.login.BaiduLoginFragment;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class BirthdayListFragment extends BaseMvpFragment<FragmentBirthdayListBinding, HomePresenter> {


    private PageRecyclerViewManager<BirthdayPO> prvm;

    @Override
    protected void initView(Bundle savedInstanceState) {
        prvm = new PageRecyclerViewManager<BirthdayPO>()
                .setContext(getContext())
                .setRecyclerView(binding.recyclerview)
                .setAdapter(new BirthdayListAdapter())
                .setDivider(true)
                .setOnItemClickListener((baseQuickAdapter, view, i) -> {
                    ToastUtil.show("点击第" + i + "个");
                    jump2Edit(prvm.getRvList().get(i));
                })
                .setOnItemLongClickListener((baseQuickAdapter, view, i) -> {
                    new XPopup.Builder(getContext())
                            //.maxWidth(600)
                            .atView(view)
                            .popupPosition(PopupPosition.Bottom)
                            .hasShadowBg(false)
                            .animationDuration(0)
                            .asAttachList(new String[]{"编辑", "删除"},
                                    new int[]{R.drawable.icon_note, R.drawable.icon_delete},
                                    (position, text) -> {
                                        ToastUtil.show("click " + text);
                                        if (position == 0) {
                                            jump2Edit(prvm.getRvList().get(i));
                                        } else if (position == 1) {
                                            AsyncUtils.run(emitter -> {
                                                // TODO: 2024/1/16 编辑
                                                BirthdayPO item = prvm.getRvList().get(i);
                                                item.setUpdateTime(System.currentTimeMillis());
                                                item.setDeleteflag((byte) 1);
                                                MainDatabase_Impl.getInstance().birthdayDao().updateItem(item);
                                                emitter.onNext("");
                                            }, data -> queryList());
                                        }
                                    })
                            .show();
                    return false;
                })
                .setRefreshLayout(binding.refreshLayout)
                .setEnableRefresh(false)
                .setEnableLoadMore(false)
                .init();
    }

    @Override
    protected void initData() {
        queryList();
    }

    @Override
    protected void initListener() {
        binding.imgEdit.setOnClickListener(v -> {
            Navigation.findNavController(binding.container).navigate(R.id.action_birthdayListFragment_to_birthdayEditFragment);
        });
//        binding.imgBackup.setOnClickListener(v -> {
//            Navigation.findNavController(binding.container).navigate(R.id.action_birthdayListFragment_to_backupFragment);
//        });
        binding.etSearch.setOnKeyListener((v, keyCode, event) -> {
            if (KeyEventUtil.isEnter(keyCode)) {
                queryList();
                return true;
            }
            return false;
        });
    }

    private void queryList() {
        AsyncUtils.run(emitter -> {
            String sql = " SELECT * FROM birthday WHERE deleteflag!=1 ";
            if (EmptyUtil.isNotEmpty(binding.etSearch.getText())) {
                sql += " AND name like '%" + binding.etSearch.getText() + "%' ";
            }
            List<BirthdayPO> list = MainDatabase_Impl.getInstance().birthdayDao().getList(new SimpleSQLiteQuery(sql));
            List<BirthdayPO> lunarAndSolarBirthdayList = BirthdayUtil.birthday2LunarSolarBirthday(list, EmptyUtil.isNotEmpty(binding.etSearch.getText()));
            emitter.onNext(lunarAndSolarBirthdayList);
        }, (Consumer<List<BirthdayPO>>) data -> {
            prvm.freshData(data);
            queryThumb();
        });
    }

    public void jump2Edit(BirthdayPO item) {
        Bundle finalArgs = new Bundle();
        finalArgs.putString("data", item.getUuid());
        finalArgs.putString("url", item.getImgUrl());
        Navigation.findNavController(binding.container).navigate(R.id.action_birthdayListFragment_to_birthdayEditFragment, finalArgs);
    }


    //region 获取缩略图
    List<String> thumbs = new ArrayList<>();

    private void queryThumb() {
        thumbs.clear();
        for (BirthdayPO item : prvm.getRvList()) {
            if (EmptyUtil.isEmpty(item.getFsids())) {
                continue;
            }
            try {
                thumbs.add(item.getFsids());
            } catch (Exception e) {
                LogUtil.e("err:", e);
            }
        }
        listInfo(thumbs);
    }

    /**
     * 查询文件
     */
    public void listInfo(List<String> fsIds) {
        BaiduNetApi.ListInfoDTO resquest = new BaiduNetApi.ListInfoDTO()
                .setAccess_token(MmkvUtil.getString(BaiduLoginFragment.BAIDUNET_ACCESS_TOKEN, ""))
                .setFsids(fsIds);
        BaiduNetApi.listInfo(resquest).subscribe(listInfoVO -> {
            if (EmptyUtil.isEmpty(listInfoVO.getList())) {
                return;
            }
            //将结果映射到diary数组中
            HashMap<String, String> fsidUrlMap = new HashMap<>();
            for (BaiduNetApi.ListInfoVO.Item item : listInfoVO.getList()) {
                if (item.getThumbs() == null) {
                    continue;
                }
                if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl4())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl4());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl3())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl3());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl2())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl2());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl1())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl1());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getIcon())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getIcon());
                }
            }
            for (BirthdayPO item : prvm.getRvList()) {
                if (EmptyUtil.isEmpty(item.getFsids())) {
                    continue;
                }
                item.setImgUrl(fsidUrlMap.get(item.getFsids()));
            }
            prvm.freshData();
        }, LogUtil::e);
    }
    //endregion
}